/**
 * Copyright (c) 2018 苍穹跃龙
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.l.configuration;

import java.io.IOException;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.mapper.LogicSqlInjector;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisMapperRefresh;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import com.l.core.mybatis.BaseMetaObjectHandler;

/**
 * @author 严秋旺
 * @date 2018-09-19
 */
@Configuration
@EnableTransactionManagement // 开启注解事务
@PropertySource("classpath:config.properties") // 导入属性文件
@MapperScan(basePackages = "com.l", annotationClass = Mapper.class)
public class RootConfigDataSource {
    private ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

    // 上面导入的属性文件中的属性会 注入到 Environment 中
    @Autowired
    private Environment env;

    @Bean(initMethod = "init", destroyMethod = "close")
    public DataSource dataSource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.username"));
        dataSource.setPassword(env.getProperty("jdbc.password"));
        dataSource.setFilters("wall,stat");
        return dataSource;
    }

    @Bean
    public MybatisSqlSessionFactoryBean sqlSessionFactory(DataSource dataSource, GlobalConfiguration globalConfig)
            throws IOException {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        sqlSessionFactory.setConfigLocation(resolver.getResource("classpath:mybatis-config.xml"));
        Resource[] mapperLocations = resolver.getResources("classpath:mapper/**/*.xml");
        sqlSessionFactory.setMapperLocations(mapperLocations);

        // 以下为mybatis-plus配置
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        sqlSessionFactory.setPlugins(new Interceptor[] { paginationInterceptor });
        sqlSessionFactory.setGlobalConfig(globalConfig);
        return sqlSessionFactory;
    }

    @Bean
    public GlobalConfiguration globalConfig() {
        GlobalConfiguration globalConfig = new GlobalConfiguration();
        /**
         * AUTO->`0`("数据库ID自增") INPUT->`1`(用户输入ID") ID_WORKER->`2`("全局唯一ID")
         * UUID->`3`("全局唯一ID")
         */
        globalConfig.setIdType(1);

        // 全局表为下划线命名设置
        globalConfig.setDbColumnUnderline(false);
        // 逻辑删除
        globalConfig.setSqlInjector(new LogicSqlInjector());
        globalConfig.setLogicNotDeleteValue("0");
        globalConfig.setLogicDeleteValue("1");
        globalConfig.setMetaObjectHandler(new BaseMetaObjectHandler(globalConfig));
        return globalConfig;
    }

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public MybatisMapperRefresh mybatisMapperRefresh(SqlSessionFactory sessionFactory) throws IOException {
        Resource[] mapperLocations = resolver.getResources("classpath:mapper/**/*.xml");
        MybatisMapperRefresh mybatisMapperRefresh = new MybatisMapperRefresh(mapperLocations, sessionFactory, true);
        return mybatisMapperRefresh;
    }

}
